package com.ekgc.addressbook.base.util;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.ekgc.addressbook.common.Contacts;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ContactMapperLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(ContactMapperLogAspect.class);

    // 定义切入点，匹配 ContactMapper 接口的所有方法
    @Pointcut("execution(* com.ekgc.addressbook.dao.mapper.ContactMapper.*(..))")
    public void contactMapperMethods() {}

    // 在方法执行前记录日志
    @Before("contactMapperMethods()")
    public void beforeContactMapperMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        logger.info("开始执行 ContactMapper 的 {} 方法，入参：{}", methodName, args);
    }

    // 在方法执行后记录日志
    @AfterReturning(pointcut = "contactMapperMethods()", returning = "result")
    public void afterContactMapperMethod(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        if (result instanceof IPage) {
            IPage<Contacts> pageResult = (IPage<Contacts>) result;
            logger.info("ContactMapper 的 {} 方法执行结束，返回结果：总记录数 = {}, 当前页记录数 = {}",
                    methodName, pageResult.getTotal(), pageResult.getRecords().size());
        } else {
            logger.info("ContactMapper 的 {} 方法执行结束，返回结果：{}", methodName, result);
        }
    }
}    